﻿using Gasgoo.ShareLibrary.Framework.Global;
using Gasgoo.ShareLibrary.Framework.iCacheProvider;
using Gasgoo.ShareLibrary.Framework.ServiceDefine;
using Orleans.Providers;
using System.Collections.Concurrent;
using System.Threading.Tasks;

namespace Gasgoo.CacheProvider
{

    /// <summary>
    /// 性能需要处理
    /// </summary>

    [StorageProvider(ProviderName = Constants.CACHE_SQLSERVE_PROVIDER)]
    public class HashProvider : GasgooServiceBase<ConcurrentDictionary<string, string>>, IHashProvider
    {
        public Task<ConcurrentDictionary<string, string>> GetAsync()
        {
            return Task.FromResult(this.State);
        }

        public Task<string> GetAsync(string field)
        {
            this.State.TryGetValue(field, out string payload);
            return Task.FromResult(payload);
        }

        public async Task RemoveAsync(string field)
        {
            this.State.TryRemove(field, out _);
            await this.WriteStateAsync();
        }

        public async Task RemoveAsync()
        {
            await this.ClearStateAsync();
        }

        public async Task SetAsync(string field, string payload)
        {
            if (this.State.ContainsKey(field))
            {
                if (this.State[field] != payload)
                {
                    this.State[field] = payload;
                    await this.WriteStateAsync();
                }
            }
            else
            {
                this.State.TryAdd(field, payload);
                await this.WriteStateAsync();
            }
        }
    }
}
